package com.yun.zf.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.yun.zf.common.admin.domain.SysUserPhone;
import com.yun.zf.common.utils.StringUtils;
import com.yun.zf.common.vo.Response;
import com.yun.zf.system.exception.CustomException;
import com.yun.zf.system.service.SysUserPhoneService;
import com.yun.zf.system.utils.WechatDecryptDataUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "微信")
@RequestMapping("/wx")
@Slf4j
public class WxController {
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String appsrcret;
    private String wxAuthUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    @Autowired
    private SysUserPhoneService  phoneService;


    @PostMapping("/getPhone")
    @ApiOperation(value = "获取手机号码")
    @DynamicParameters(properties = {
            @DynamicParameter(name = "encryptedData",value = "加密数据",example = "1",required = true),
            @DynamicParameter(name = "sessionKey",value = "会话key",example = "1",required = true),
            @DynamicParameter(name = "iv",value = "iv",example = "1",required = true)
    })
    public Response getPhone(@RequestBody Map<String, String> map) {
        WechatDecryptDataUtil dataUtil = new WechatDecryptDataUtil();
        String iphone = "";
        try {
            String iphoneStr = dataUtil.wxDecrypt(map.get("encryptedData"), map.get("sessionKey"), map.get("iv"));
            if (StringUtils.isNotBlank(iphoneStr)) {
                JSONObject jsonObject = JSON.parseObject(iphoneStr);
                iphone = jsonObject.getString("purePhoneNumber");
            }
        } catch (Exception e) {
            throw new CustomException("手机号码解密失败");
        }

        if (StringUtils.isNotBlank(iphone)) {
            // 查询数据是否存在
            SysUserPhone phone = phoneService.getByIphone(Long.parseLong(iphone));
            if (phone != null) {
                return Response.success();
            } else {
                phoneService.bindPhone(iphone);
            }
        }
        Map<String, String> phoneMap = new HashMap<>();
        phoneMap.put("phone", iphone);
        return Response.success(phoneMap);
    }
}
